/**
 * Collections 搜索 Hook
 * 提供集合搜索和过滤功能
 */
import { useMemo } from 'react';
import type { SpaceCollection } from '@/types';
import type { SearchOptions } from './types';

/**
 * 搜索和过滤集合列表
 * @param collections - 集合列表
 * @param searchQuery - 搜索关键词
 * @param options - 搜索选项
 * @returns 过滤后的集合列表
 */
export function useSearchCollections(
    collections: SpaceCollection[],
    searchQuery: string,
    options?: SearchOptions
): SpaceCollection[] {
    return useMemo(() => {
        const query = searchQuery.trim();
        
        // 如果没有搜索关键词，返回全部集合
        if (!query) {
            return collections;
        }

        const searchTerm = options?.caseSensitive ? query : query.toLowerCase();

        // 过滤集合：匹配集合名称或标签页的标题/URL/域名
        return collections.filter((collection) => {
            const collectionName = options?.caseSensitive
                ? collection.collection.name
                : collection.collection.name.toLowerCase();

            // 检查集合名称是否匹配
            if (collectionName.includes(searchTerm)) {
                return true;
            }

            // 检查是否有标签页匹配
            return collection.tabs.some((tab) => {
                const title = options?.caseSensitive ? tab.title : tab.title.toLowerCase();
                const url = options?.caseSensitive ? tab.url : tab.url.toLowerCase();
                const domain = options?.caseSensitive ? tab.domain : tab.domain.toLowerCase();

                return (
                    title.includes(searchTerm) ||
                    url.includes(searchTerm) ||
                    domain.includes(searchTerm)
                );
            });
        });
    }, [collections, searchQuery, options?.caseSensitive]);
}
